package com.yy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.constants.CategoryConstant;
import com.yy.domain.Category;
import com.yy.ex.BusinessException;
import com.yy.service.CategoryService;
import com.yy.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
* @author yy5
* @description 针对表【category(产品类目)】的数据库操作Service实现
* @createDate 2023-11-27 20:47:04
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 全查询，不分页
     */
    @Override
    public List<Category> loadCategorys() {
        return this.categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .orderByDesc(Category::getSeq,Category::getUpdateTime)
        );



    }

    /**
     * 查询所有可用父分类列表
     *
     * @return
     */
    @Override
    public List<Category> loadParentCategorys() {
        return this.categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId,0L)
                .eq(Category::getStatus,1)
                .orderByDesc(Category::getSeq,Category::getUpdateTime)
        );
    }

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @Override
    @Caching(evict = {
            @CacheEvict(key = CategoryConstant.CATEGORY_PARENT_LIST),
            @CacheEvict(key = CategoryConstant.CATEGORY_LIST)
    })
    public Integer addCategory(Category category) {
        //查询分类表中是否有该添加的分类
        Long count=categoryMapper.selectCount(new LambdaQueryWrapper<Category>()
                .eq(Category::getCategoryName,category.getCategoryName())
        );
        if (count>0){
            throw new BusinessException("该分类已经存在");
        }
        if (ObjectUtils.isEmpty(category.getParentId())||category.getParentId().equals(0)){
            category.setParentId(0L);
        }else {
            //校验
            if (ObjectUtils.isEmpty(categoryMapper.selectById(category.getParentId()))){
                throw new BusinessException("该父分类不存在");
            }
        }
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        return categoryMapper.insert(category);
    }


}




